<template>

    <!-- paypal支付 -->
    <!-- 支付轮询中 -->
    <div class="payment-paypal">

        <button @click="doPaying()">
            <img src="@/assets/images/payment-paypal-normal.png" />
            <img src="@/assets/images/payment-paypal-disabled.png" />
        </button>

        <!-- 轮询对话框 -->
        <UxDialog :visible="true" :can-close="false" v-show="!!dialog" class="payment-paypal-dialog">

            <div class="order-payment-close" @click="onClose()"><svg-icon name="dialog-close-medium" /></div>

            <!-- 等待验证 -->
            <div class="order-payment-pending" v-if="dialog && dialog.substatus == 'pending'">
                <figure><img src="https://img.podpartner.com/static/images-20230202/order-pending.png"></figure>
                <h4><img src="@/assets/images/pay-pending.gif" alt="" /></h4>
                <p>Payment is being processed. Please do not pay again.</p>
            </div>

            <!-- 轮询中 -->
            <div class="order-payment-polling" v-if="dialog && dialog.substatus == 'polling'">
                <figure><img src="https://img.podpartner.com/static/images-20230202/order-paying.png"></figure>
                <h4><img src="@/assets/images/pay-loading.gif" alt="" /></h4>
                <p>Paying, please wait <br> patiently</p>
            </div>

            <!-- 失败 -->
            <div class="order-payment-failure" v-show="dialog && dialog.substatus == 'failure'">
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/payment/order-payment-failure.png" alt="">
                    <strong>Payment failed</strong>
                    <span v-text="dialog && dialog.error"></span>
                </figure>
                <button type="primary" @click="onClose()">OK</button>
            </div>

            <!-- 请求超时 -->
            <div class="order-payment-timeout" v-show="dialog && dialog.substatus == 'timeout'">
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/payment/order-payment-network.png" alt="">
                    <strong>The connection has timed out.</strong>
                </figure>
                <button type="primary" @click="doPaying()">Try again</button>
            </div>

        </UxDialog>

    </div>

</template>
<script>
import PaymentUtils from '@/utils/PaymentUtils.js';
export default {
    name: "OrderPaymentPaypal",
    props: ["option"],
    data () {
        return {
            dialog: '',
            popup: null, // 支付弹窗
            timer: null,
        };
    },

    methods: {

        popupOpen (payment) {
            // if (payment == "wallet") {
            // var style =
            //     "<style>.spinner {height: 100%;width: 100%;position: fixed;top: 0;left: 0;z-index: 10;}.spinner .spinWrap {width: 200px;height: 100px;position: fixed;top: 42%;left: 50%;margin-left: -100px;margin-top: -50px;}.spinner .spinnerImage {margin: 28px 0 0 -25px;}.spinner .loader,.spinner .spinnerImage {height: 100px;width: 100px;position: absolute;top: 0;left: 50%;opacity: 1;filter: alpha(opacity=100);}.spinner .loader {margin: 0 0 0 -55px;background-color: transparent;-webkit-animation: rotation 0.7s linear infinite;-moz-animation: rotation 0.7s infinite linear;-o-animation: rotation 0.7s infinite linear;animation: rotation 0.7s linear infinite;border: 5px solid #cbcbca;border-top-color: #2380be;border-radius: 100%;}.spinner .loadingMessage {-webkit-box-sizing: border-box;-moz-box-sizing: border-box;-ms-box-sizing: border-box;box-sizing: border-box;width: 100%;margin-top: 125px;text-align: center;z-index: 100;outline: none;}@-webkit-keyframes rotation {0% {-webkit-transform: rotate(0deg);}to {-webkit-transform: rotate(359deg);}}@-moz-keyframes rotation {0% {-moz-transform: rotate(0deg);}to {-moz-transform: rotate(359deg);}}@-o-keyframes rotation {0% {-o-transform: rotate(0deg);}to {-o-transform: rotate(359deg);}}@keyframes rotation {0% {transform: rotate(0deg);}to {transform: rotate(359deg);}}@media only screen and (max-width: 768px) {.spinner .spinWrap {width: 200px;height: 100px;position: fixed;top: 40%;left: 50%;margin-left: -93px;margin-top: -50px;}}</style>";
            // var body =
            //     '<div class="spinner" id="preloader"><div class="spinWrap"><p class="spinnerImage"><img src=""></p><p class="loader"></p><p class="loadingMessage">Processing...</p><p class="loadingSubHeading"></p></div></div>';
            // // this.popup = window.open('/bridge/payment.html', "_blank");

            // this.popup = window.open("about:blank");
            // this.popup.document.write(style + body);
            // this.popupListener();
            // }else{
            // var style =
            //     "<style>.spinner {height: 100%;width: 100%;position: fixed;top: 0;left: 0;z-index: 10;}.spinner .spinWrap {width: 200px;height: 100px;position: fixed;top: 42%;left: 50%;margin-left: -100px;margin-top: -50px;}.spinner .spinnerImage {margin: 28px 0 0 -25px;}.spinner .loader,.spinner .spinnerImage {height: 100px;width: 100px;position: absolute;top: 0;left: 50%;opacity: 1;filter: alpha(opacity=100);}.spinner .loader {margin: 0 0 0 -55px;background-color: transparent;-webkit-animation: rotation 0.7s linear infinite;-moz-animation: rotation 0.7s infinite linear;-o-animation: rotation 0.7s infinite linear;animation: rotation 0.7s linear infinite;border: 5px solid #cbcbca;border-top-color: #2380be;border-radius: 100%;}.spinner .loadingMessage {-webkit-box-sizing: border-box;-moz-box-sizing: border-box;-ms-box-sizing: border-box;box-sizing: border-box;width: 100%;margin-top: 125px;text-align: center;z-index: 100;outline: none;}@-webkit-keyframes rotation {0% {-webkit-transform: rotate(0deg);}to {-webkit-transform: rotate(359deg);}}@-moz-keyframes rotation {0% {-moz-transform: rotate(0deg);}to {-moz-transform: rotate(359deg);}}@-o-keyframes rotation {0% {-o-transform: rotate(0deg);}to {-o-transform: rotate(359deg);}}@keyframes rotation {0% {transform: rotate(0deg);}to {transform: rotate(359deg);}}@media only screen and (max-width: 768px) {.spinner .spinWrap {width: 200px;height: 100px;position: fixed;top: 40%;left: 50%;margin-left: -93px;margin-top: -50px;}}</style>";
            // var body =
            //     '<div class="spinner" id="preloader"><div class="spinWrap"><p class="spinnerImage"><img src=""></p><p class="loader"></p><p class="loadingMessage">Processing...</p><p class="loadingSubHeading"></p></div></div>';

            // this.popup = window.open("about:blank");
            // this.popup.document.write(style + body);

            this.popup = window.open('/bridge/paying.html', "_blank");
            this.popupListener();
        },
        popupListener () {
            if (!this.popup) {
                // 没有了，不用管了
            } else if (this.popup.closed) {
                // 关闭了
                // 可以做一些交互
                // this.popupClose();
                this.popup = null;
            } else if (this._isDestroyed) {
                this.popupClose()
            } else {
                // 轮询
                setTimeout(this.popupListener, 200);
            }
        },
        // 关闭弹窗
        popupClose () {

            setTimeout(() => {
                if (this.popup) {
                    try {
                        this.popup.close();
                        this.popup = null;
                    } catch (error) {
                        console.log(error)
                    }
                }
            }, 10);
        },


        // 关闭弹窗
        onClose () {

            if (!this.dialog) {

            } else if (this.dialog.quit) {
                this.$emit('global:ORDER_BULK_CLOSE')
            } else {
                this.dialog.callback({
                    action: 'cancel',
                    message: 'Close paying windows'
                })
            }
        },

        // 开始支付
        doPaying () {
            const doContinue = () => {
                // 取跳转地址
                this.dialog = {
                    substatus: 'polling', // polling|pending|delayed|success|failure|timeout
                    error: '',
                    polldate: '',
                    batch_label: '',
                    quit: false,
                    callback: (option) => {
                        if (!this.dialog) {
                            // 多次回调问题
                        } else if (option.action == 'success') {
                            // 成功
                            this.dialog = null;
                            this.popupClose();
                            this.$emit('statusChange', {
                                payment: 'paypal',
                                action: 'success',
                            })
                        } else {
                            // 其他情况
                            const substatus = this.dialog.substatus
                            this.dialog = null;
                            this.popupClose();
                            this.$emit('statusChange', {
                                payment: 'paypal',
                                action: 'cancel',
                                substatus: substatus,
                                message: option.message,
                            })
                        }
                    }
                }

                // 获取
                this.payApprove()
            }

            this.popupOpen()
            this.$emit('statusChange', {
                payment: 'paypal',
                action: 'before',
                callback: res => {
                    if (!res) {
                        // 不继续
                        this.popupClose();
                    } else {
                        doContinue()
                    }
                }
            })
        },

        // 设置父级状态
        setParentStatus (status) {
            const parent = this.$parent.$parent;
            if (parent) {
                parent.status = status
            }
        },

        // 获取paypal跳转地址
        payApprove () {

            const pay = () => {
                const paycode = { paypal: 1, card: 2, payoneer: 3, wallet: 4 }['paypal'];

                // const res = await this.$http("Wallet.putRecharge", { amount: value });
                if (this.option.action == 'recharge') {
                    // 钱包充值
                    return this.$http("Wallet.putRecharge", {
                        amount: this.option.amount,
                    })
                } else if (this.option.action == 'batch') {
                    // 批量支付
                    return this.$http("Order.batchPayOrder", {
                        order_code: this.option.codes,
                        payment: paycode,
                    })
                } else {
                    //  单个支付
                    return this.$http(
                        "Order.payOrder/" + this.option.codes,
                        { payment: paycode }
                    );
                }
            }


            return pay().then(response => {

                const data = response.data || {}
                const openUrl = data.approve_url || data.approved_url;


                if (!this.dialog) {
                    // 没有对话框了，不管了
                } else if (response.code === 4055) {
                    // 黑名单用户
                    this.setParentStatus('blackuser')
                    this.dialog = null;
                    this.popupClose();

                } else if (response.code === 4001) {
                    // 状态异常，退出
                    this.dialog = null;
                    this.popupClose();
                    this.$emit('statusChange', {
                        payment: 'paypal',
                        action: 'reload',
                        message: response.msg
                    })

                } else if (response.code !== 0 || !openUrl) {

                    if (data.state === 1) {
                        // 库存不足
                        this.dialog = null;
                        this.popupClose();
                        this.$emit('statusChange', {
                            payment: 'paypal',
                            action: 'stock',
                            stocks: data.list || [],
                            message: response.msg
                        })

                    } else {
                        // 可能是网络失败
                        this.dialog.substatus = 'timeout'
                        this.popupClose();
                    }


                    // return Promise.reject(response.msg || "Please check your network connection")
                } else {
                    !this.popup && this.popupOpen()
                    if (this.popup) {
                        this.popup.location = openUrl;
                        this.dialog.polldate = data.money_order + '/' + data.amount;
                        this.dialog.batch_label = data.batch_label || ''
                        this.payPolling()
                    } else {
                        // 异常
                        this.dialog.substatus = 'failure'
                        this.dialog.error = 'Open window tag failure!'
                    }
                }
            })
        },

        // 轮询请求状态
        payPolling () {

            const option = {
                payby: 'paypal',
                action: this.option.action,
                payment: this.option.payment,
                codes: this.option.codes,
                polldate: this.dialog ? this.dialog.polldate : '',
                batch_label: this.dialog ? this.dialog.batch_label : '',
            }

            // 有dialog才轮询
            this.dialog && PaymentUtils.checkPaymentStatus(option).then(info => {

                // 成功
                if (!this.dialog) {
                    // 没有弹窗，不管了
                } else if (info.status == 'success') {
                    // 成功
                    this.dialog.callback({
                        action: 'success',
                        message: info.message
                    })
                } else if (info.status == 'failure') {
                    // 失败
                    if (option.action == 'batch' && info.data && info.data.length > 0) {
                        this.dialog.substatus = 'failure'
                        this.dialog.error = "The following orders are in the payment process:" + info.data.join(",");
                        this.dialog.quit = true;
                    } else {
                        this.dialog.substatus = 'failure'
                        this.dialog.error = info.message
                    }

                } else if (/delayed/.test(info.status)) {
                    // 延时到账，刷新订单
                    this.dialog = null;
                    this.popupClose();
                    this.$emit('statusChange', {
                        payment: 'paypal',
                        action: 'reload',
                        message: response.msg
                    })
                } else if (/polling|pending/.test(info.status)) {
                    // 支付中
                    this.dialog.substatus = info.status
                    setTimeout(this.payPolling, 2000);
                }

            }).catch(info => {
                // 失败，网络请求等失败
                this.dialog && setTimeout(this.payPolling, 2000);
            })
        }

    },
    beforeDestroy () {
        this.dialog = '';
        this.popup && this.popupClose()
    }
};
</script>
<style lang="scss" scoped>
.payment-paypal {
    & > button {
        width: 100%;
        height: 48px;
        background: #ffc439;
        border-radius: 8px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s;
        border: none;
        &:hover {
            // background: #ffa600;
            opacity: 0.6;
        }
        img {
            width: 102px;
            height: 32px;
            &:nth-child(2) {
                display: none;
            }
        }
    }

    &[disabled] button {
        background: #d8d8d8;
        color: #ffffff;
        pointer-events: none;
        user-select: none;
        img {
            &:nth-child(1) {
                display: none;
            }
            &:nth-child(2) {
                display: block;
            }
        }
    }
}

.order-payment-close {
    z-index: 1;
    position: absolute;
    right: 4px;
    top: 4px;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #555;
    transition: all 0.3s;
    cursor: pointer;
    border-radius: 4px;
    svg {
        width: 10px;
        height: 10px;
    }
    &:hover {
        background-color: rgba(255, 0, 0, 0.1);
        color: #8c1c14;
    }
}

.order-payment-pending,
.order-payment-polling {
    width: 320px;
    height: 414px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin: 0 auto;
    & > figure {
        width: 66px;
        height: 66px;
        img {
            width: 100%;
            height: 100%;
        }
    }
    & > h4 {
        height: 8px;
        margin-top: 16px;
        img {
            width: 40px;
            height: 8px;
        }
    }
    & > p {
        margin: 26px 20px 0;
        font-size: 20px;
        font-weight: bold;
        color: #000000;
        line-height: 24px;
        text-align: center;
    }
}

.order-payment-failure,
.order-payment-timeout {
    width: 320px;
    height: 414px;
    display: flex;
    flex-direction: column;
    align-items: center;

    & > figure {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        img {
            width: 80px;
            height: 80px;
        }

        strong {
            margin: 16px 20px 0;
            font-size: 18px;
            color: #000000;
            line-height: 28px;
            text-align: center;
        }
        span {
            margin: 8px 20px;
            font-size: 14px;
            color: #555555;
            line-height: 18px;
            text-align: center;
            white-space: pre-wrap;
            overflow: hidden;
            word-break: break-all;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 4;
            -webkit-box-orient: vertical;
        }
    }

    & > button {
        height: 38px;
        line-height: 36px;
        width: 280px;
        margin-bottom: 30px;
        font-size: 14px;
    }
}
</style>
